package com.iflytek.aidemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.google.gson.internal.LinkedTreeMap;
import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.model.ImageRecord;
import com.iflytek.aidemo.model.WrongQuestionRecord;
import com.iflytek.aidemo.util.KeyConfig;
import com.iflytek.aidemo.util.OSSCallback;
import com.iflytek.aidemo.util.OssUtil;
import com.iflytek.aidemo.util.SessionManager;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class ImageAlbumShow extends AppCompatActivity {
    private ImageView picture;
    private Uri imageUri;
    private ImageView Return_page;
    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    private static final int PERMISSION_REQUEST_CODE = 3;

    // 接受前一个Intent传入的id
    private Bundle bundle;
    private int Show_Choice;
    private String currentPhotoPath; // 存储当前照片的路径

    private TextView detailedCountText;
    private TextView tvCorrectBadge;
    private TextView tvWrongBadge;
    private LinearLayout statsBar;
    private TextView tvStats;

    // 新布局初始化
    private LinearLayout contentPanel;
    private LinearLayout bottomBar;
    private Button btn_retake;
    private Button btn_unknown;
    private FrameLayout imageArea;
    private boolean isPanelExpanded = false;
    private float startY = 0;
    private float currentY = 0;
    private static final float SWIPE_THRESHOLD = 100f;
    private static final float PANEL_INIT_VISIBLE_HEIGHT_DP = 150f; // 上划框初始露出高度
    private static final float COUNT_TEXT_HEIGHT_DP = 80f; // 统计结果高度，与XML一致
    private int contentPanelHeight = 0;
    private int countTextHeight = 0;

    private int correctCount = 0; // 正确题目数
    private int wrongCount = 0;   // 错误题目数

    private ApiService apiService = new ApiServiceImpl(); // OSS上传完成后调用接口服务
    private OssUtil ossUtil = new OssUtil(
            this, KeyConfig.osstpdz,
            KeyConfig.ossDirectory, KeyConfig.accessStsToken,
            KeyConfig.accessKeyId, KeyConfig.accessKeySecret,
            KeyConfig.endpoint, KeyConfig.bucketName);//oss上传图片

    // 存储上传到OSS后的图片URL
    private String ossImageUrl = "";

    private int recordId_ = -1; // 初始化为-1，表示未赋值

    private String Correct = "";
    private String originQuestion= "";

    private SessionManager sessionManager;

    private int flag = -1;
    private int IDX = 0;

    // 1. 新增错题数据结构
    private static class ErrorQuestion {
        int index; // 序号
        int x1, y1, x2, y2; // 坐标
        String ocrResult;
        String correctAnswer;
        private boolean isUploaded = false; // 图片是否已上传
        ErrorQuestion(int index, int x1, int y1, int x2, int y2, String ocrResult, String correctAnswer) {
            this.index = index;
            this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
            this.ocrResult = ocrResult;
            this.correctAnswer = correctAnswer;
        }
        public boolean isUploaded() { return isUploaded; }
        public void setUploaded(boolean uploaded) { isUploaded = uploaded; }
    }
    private List<ErrorQuestion> errorQuestions = new ArrayList<>();
    private int currentQuestionIndex = 0;
    private ImageView croppedQuestionImage;
    private TextView ocrResultText, correctAnswerText;
    private LinearLayout questionIndexContainer;

    /**
     * OSS上传图片
     *
     * @param imgurl 图片本地路径
     */
    private void OSSImag1(String imgurl) {
        flag = 1;
        Log.d("flag", "flag1: " + flag);
        if (imgurl == null || imgurl.isEmpty()) {
            Log.e("OSSUpload", "图片路径为空，无法上传 - imgurl: " + (imgurl != null ? imgurl : "null"));
            return;
        }

        Log.d("OSSUpload", "开始上传图片 - 本地路径1: " + imgurl);

        ossUtil.uploadImage(imgurl, new OSSCallback() {
            @Override
            public void onSuccess(final List<String> allPath) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 上传成功
                        if (allPath != null && !allPath.isEmpty()) {
                            ossImageUrl = allPath.get(0).replaceFirst("(?<!/)app/", "/app/");
                            Log.d("OSSUpload", "上传成功，OSS路径1: " + ossImageUrl);

                            // 在这里可以添加上传成功后的业务逻辑
                            // 调用uploadImageRecord上传记录到服务器
                                uploadImageRecordToServer(ossImageUrl);
                            // 例如：将OSS路径发送到服务器，更新UI等
//                            Toast.makeText(ImageAlbumShow.this, "图片已成功上传至OSS", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("OSSUpload", "上传成功但返回路径为空");
                        }
                    }
                });
            }

            @Override
            public void onFailure(ClientException clientException, ServiceException serviceException) {
                // 上传失败
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder errorMsg = new StringBuilder("上传失败");
                        Log.e("OSSUpload", "上传失败 - 详细信息:");

                        if (clientException != null) {
                            errorMsg.append(" - 客户端异常: ").append(clientException.getMessage());
                            Log.e("OSSUpload", "客户端异常", clientException);
                        }

                        if (serviceException != null) {
                            errorMsg.append(" - 服务端异常: ")
                                    .append(serviceException.getErrorCode())
                                    .append(" (").append(serviceException.getRawMessage()).append(")");
                            Log.e("OSSUpload", "服务端异常 - ErrorCode: " + serviceException.getErrorCode(), serviceException);
                        }

                        Log.e("OSSUpload", errorMsg.toString());
                        Toast.makeText(ImageAlbumShow.this, errorMsg.toString(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sessionManager = new SessionManager(this);
        setContentView(R.layout.activity_image_album_show);

        // 获取上一个Activity传递的参数
        bundle = this.getIntent().getExtras();
        Show_Choice = bundle.getInt("id");

        // 根据传入的ID执行相应操作
        switch (Show_Choice) {
            case TAKE_PHOTO:
                // 检查相机和存储权限
                if (checkCameraPermissions()) {
                    dispatchTakePictureIntent();
                }
                break;

            case CHOOSE_PHOTO:
                // 检查存储权限
                if (checkStoragePermission()) {
                    openAlbum();
                }
                break;

            default:
                Toast.makeText(this, "无效的操作类型", Toast.LENGTH_SHORT).show();
                finish();
                break;
        }




        // 初始化原有组件
        picture = findViewById(R.id.V_Image);
        Return_page = findViewById(R.id.Return_Back_to_page1);

        // 新布局初始化
        imageArea = findViewById(R.id.imageArea);
        contentPanel = findViewById(R.id.contentPanel);
        bottomBar = findViewById(R.id.bottomBar);
        btn_retake = findViewById(R.id.btn_retake);
        btn_unknown = findViewById(R.id.btn_unknown);
        detailedCountText = findViewById(R.id.detailedCountText);
        croppedQuestionImage = findViewById(R.id.croppedQuestionImage);
        ocrResultText = findViewById(R.id.ocrResultText);
        correctAnswerText = findViewById(R.id.correctAnswerText);
        questionIndexContainer = findViewById(R.id.questionIndexContainer);

        // 保证底部操作栏始终在最顶层
        bottomBar.bringToFront();

        // 布局完成后动态设置初始translationY
        contentPanel.post(new Runnable() {
            @Override
            public void run() {
                contentPanelHeight = contentPanel.getHeight();
                float collapsedY = contentPanelHeight - dpToPx(PANEL_INIT_VISIBLE_HEIGHT_DP);
                contentPanel.setTranslationY(collapsedY);
            }
        });

        // 保证contentPanel始终有手势监听
        contentPanel.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return handleSwipeGesture(event);
            }
        });

        // ScrollView不拦截下划手势
        ScrollView scrollView = contentPanel.findViewById(R.id.scrollView);
        if (scrollView != null) {
            scrollView.setOnTouchListener(new View.OnTouchListener() {
                float startY = 0;
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            startY = event.getY();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            float deltaY = event.getY() - startY;
                            // 如果是下划且已到顶部，交给外层处理
                            if (deltaY > 0 && !v.canScrollVertically(-1)) {
                                return false;
                            }
                            break;
                    }
                    return false;
                }
            });
        }


        /**
         * 返回，从照片显示到主页面
         */
        Return_page.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("IDX", "IDX: " + IDX);
                Intent intent = new Intent();
                intent.setClass(ImageAlbumShow.this, MainActivity.class);
                startActivity(intent);
            }
        });

        //点击加入错题集
        btn_unknown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("IDX1", "IDX: " + IDX);
                int idx = IDX;
                if (idx < 0 || idx >= errorQuestions.size()) return;
                currentQuestionIndex = idx;
                ErrorQuestion q = errorQuestions.get(idx);

                System.out.println("sssssss"+q.ocrResult);

                // 检查图片是否已上传
                if (!q.isUploaded()) {
                    // 裁剪图片
                    Bitmap src = ((BitmapDrawable) picture.getDrawable()).getBitmap();
                    Bitmap cropped = Bitmap.createBitmap(src, q.x1, q.y1, q.x2 - q.x1, q.y2 - q.y1);
                    croppedQuestionImage.setImageBitmap(cropped);
                    // 上传图片并标记为已上传
                    OSSImag2(cropped);
                    q.setUploaded(true); // 标记为已上传
                } else {
                    // 缓存中没有则重新裁剪（罕见情况）
                    Bitmap src = ((BitmapDrawable) picture.getDrawable()).getBitmap();
                    Bitmap cropped = Bitmap.createBitmap(src, q.x1, q.y1, q.x2 - q.x1, q.y2 - q.y1);
                    croppedQuestionImage.setImageBitmap(cropped);
                }
                Correct = q.correctAnswer;
                originQuestion = q.ocrResult;
            }
        });

        // 再来一张按钮点击事件
        btn_retake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清空当前数据
                clearCurrentData();

                // 根据之前的拍照方式重新拍照
                if (Show_Choice == TAKE_PHOTO) {
                    // 重新拍照
                    if (checkCameraPermissions()) {
                        dispatchTakePictureIntent();
                    }
                } else if (Show_Choice == CHOOSE_PHOTO) {
                    // 重新选择照片
                    if (checkStoragePermission()) {
                        openAlbum();
                    }
                }
            }
        });

        // 解决Android 7.0文件权限问题
        if (Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        setupQuestionIndexSelector();
        showQuestion(0);
    }

    // 展开面板并滚动到指定错题
    private void expandPanelAndScrollTo(int errorId) {
        expandPanel();
        // TODO: 滚动到错题详情（可用ScrollView/RecyclerView定位）
    }

    // 上划展开面板
    private void expandPanel() {
        if (isPanelExpanded) return;
        isPanelExpanded = true;
        contentPanel.animate()
                .translationY(0)
                .setDuration(300)
                .start();
        // 上滑展开时隐藏底部统计条
        if (statsBar != null) statsBar.setVisibility(View.GONE);
    }

    // 下划收起面板
    private void collapsePanel() {
        if (!isPanelExpanded) return;
        isPanelExpanded = false;
        float collapsedY = contentPanelHeight - dpToPx(PANEL_INIT_VISIBLE_HEIGHT_DP);
        contentPanel.animate()
                .translationY(collapsedY)
                .setDuration(300)
                .start();
        // 下滑收起时显示底部统计条
        if (statsBar != null) statsBar.setVisibility(View.VISIBLE);
    }

    // 手势处理
    private boolean handleSwipeGesture(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = event.getY();
                return true;
            case MotionEvent.ACTION_MOVE:
                currentY = event.getY();
                float deltaY = startY - currentY;
                if (deltaY > SWIPE_THRESHOLD && !isPanelExpanded) {
                    expandPanel();
                    return true;
                } else if (deltaY < -SWIPE_THRESHOLD && isPanelExpanded) {
                    collapsePanel();
                    return true;
                }
                return true;
            case MotionEvent.ACTION_UP:
                currentY = event.getY();
                float finalDeltaY = startY - currentY;
                if (!isPanelExpanded && finalDeltaY > SWIPE_THRESHOLD) {
                    expandPanel();
                } else if (isPanelExpanded && finalDeltaY < -SWIPE_THRESHOLD) {
                    collapsePanel();
                }
                return true;
        }
        return false;
    }

    // 检查相机和存储权限
    private boolean checkCameraPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
            return false;
        }
        return true;
    }

    // 检查存储权限
    private boolean checkStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
            return false;
        }
        return true;
    }

    // 启动相机拍照
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 确保有相机应用可以处理该Intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                ex.printStackTrace();
                Toast.makeText(this, "创建图片文件失败", Toast.LENGTH_SHORT).show();
                return;
            }

            if (photoFile != null) {
                // 根据Android版本选择不同的Uri处理方式
                if (Build.VERSION.SDK_INT < 24) {
                    imageUri = Uri.fromFile(photoFile);
                } else {
                    // 使用FileProvider获取内容Uri
                    imageUri = FileProvider.getUriForFile(this,
                            "com.iflytek.aidemo.fileprovider",
                            photoFile);
                }

                // 添加URI权限（针对Android 7.0+）
                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(takePictureIntent, TAKE_PHOTO);
            }
        }
    }

    // 创建图片文件
    private File createImageFile() throws IOException {
        // 使用应用私有目录，不需要WRITE_EXTERNAL_STORAGE权限
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
        File image = File.createTempFile(
                imageFileName,  /* 前缀 */
                ".jpg",         /* 后缀 */
                storageDir      /* 目录 */
        );

        // 保存文件路径用于后续加载图片
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    // 打开相册
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限已授予，根据请求的权限类型执行相应操作
                    if (permissions[0].equals(Manifest.permission.CAMERA)) {
                        dispatchTakePictureIntent();
                    } else if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        openAlbum();
                    }
                } else {
                    Toast.makeText(this, "权限被拒绝，无法执行操作", Toast.LENGTH_SHORT).show();
                    finish(); // 权限被拒绝，关闭当前Activity
                }
                break;
        }
    }

    // 处理Activity返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    // 拍照返回，使用之前保存的Uri
                    try {
                        Log.d("拍照结果", "Uri: " + imageUri);
                        Log.d("拍照结果", "路径: " + currentPhotoPath);

                        // 从Uri加载图片
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                        // 处理图片（调用AI识别）
                        Log.d("TAG", "调用AI识别");
                        bitmap = image_itr(bitmap, currentPhotoPath);

                        // 显示处理后的图片
                        picture.setImageBitmap(bitmap);

                        Toast.makeText(this, "拍照成功", Toast.LENGTH_SHORT).show();

                        picture.post(new Runnable() {
                            @Override
                            public void run() {
                                setupQuestionIndexSelector();
                                if (!errorQuestions.isEmpty()) {
                                    showQuestion(0);
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this, "加载图片失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    break;

                case CHOOSE_PHOTO:
                    // 从相册选择返回
                    if (data != null) {
                        Uri selectedImageUri = data.getData();
                        System.out.println("url:"+selectedImageUri);
                        if (selectedImageUri != null) {
                            try {
                                // 从Uri加载图片
//                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                                // 处理图片（调用AI识别）
                                String imagePath = getImagePath(selectedImageUri, null);
                                if (imagePath != null) {
                                    // 从路径加载图片
                                    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                                    // 处理图片（调用AI识别）
                                    Log.d("TAG", "调用AI识别");
                                    bitmap = image_itr(bitmap, imagePath); // 传递图片路径用于上传
                                    // 显示处理后的图片
                                    if (bitmap != null) {
                                        picture.setImageBitmap(bitmap);
                                    }
                                    // 显示处理后的图片
                                    picture.setImageBitmap(bitmap);
                                }

                                //Toast.makeText(this, "图片选择成功", Toast.LENGTH_SHORT).show();

                                picture.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        setupQuestionIndexSelector();
                                        if (!errorQuestions.isEmpty()) {
                                            showQuestion(0);
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(this, "加载图片失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    break;
            }
        } else {
            Toast.makeText(this, "操作取消", Toast.LENGTH_SHORT).show();
            finish(); // 操作取消，关闭当前Activity
        }
    }

    // 4.4及以上系统处理图片的方法
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);

        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            }
            else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        }
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        }
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }

        if (imagePath != null) {
            try {
                // 从路径加载图片
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                // 处理图片（调用AI识别）
                bitmap = image_itr(bitmap, imagePath);
                // 显示处理后的图片
                picture.setImageBitmap(bitmap);

                picture.post(new Runnable() {
                    @Override
                    public void run() {
                        setupQuestionIndexSelector();
                        if (!errorQuestions.isEmpty()) {
                            showQuestion(0);
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "图片处理失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "无法获取图片路径", Toast.LENGTH_SHORT).show();
        }
    }

    // 4.4以下系统处理图片的方法
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        if (imagePath != null) {
            try {
                // 从路径加载图片
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                // 处理图片（调用AI识别）
                bitmap = image_itr(bitmap, imagePath);

                // 显示处理后的图片
                picture.setImageBitmap(bitmap);

                picture.post(new Runnable() {
                    @Override
                    public void run() {
                        setupQuestionIndexSelector();
                        if (!errorQuestions.isEmpty()) {
                            showQuestion(0);
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "图片处理失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "无法获取图片路径", Toast.LENGTH_SHORT).show();
        }
    }

    // 获取图片路径的方法
    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过URI和选择条件获取图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    // 处理图片并调用AI识别
    private Bitmap image_itr(Bitmap imageBitmap, String imagePath) {
        if (imageBitmap == null) {
            Toast.makeText(this, "图片为空", Toast.LENGTH_SHORT).show();
            return null;
        }

        try {
            // 将Bitmap转换为字节数组
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
            WebITR.imageByteArray = stream.toByteArray();
            stream.close();

            // 调用AI识别API
            WebITR.ResponseData responseData = WebITR.call_itr(null);
            if (responseData == null) {
                Toast.makeText(this, "AI识别失败，返回null", Toast.LENGTH_SHORT).show();
                return imageBitmap;
            }

            // 解析识别结果
            LinkedTreeMap dataMap = (LinkedTreeMap) responseData.getData();
            if (dataMap == null) {
                Toast.makeText(this, "AI识别结果为空", Toast.LENGTH_SHORT).show();
                return imageBitmap;
            }

            LinkedTreeMap itrResultMap = (LinkedTreeMap) dataMap.get("ITRResult");
            if (itrResultMap == null) {
                Toast.makeText(this, "ITRResult为空", Toast.LENGTH_SHORT).show();
                return imageBitmap;
            }

            LinkedTreeMap multiLineInfoMap = (LinkedTreeMap) itrResultMap.get("multi_line_info");
            ArrayList impLineInfoList = (ArrayList) multiLineInfoMap.get("imp_line_info");

            if (impLineInfoList == null || impLineInfoList.isEmpty()) {
                Toast.makeText(this, "未识别到题目", Toast.LENGTH_SHORT).show();
                return imageBitmap;
            }

            // 获取识别文本数组
            ArrayList recogResultList = (ArrayList) itrResultMap.get("recog_result");
            ArrayList lineWordResultList = null;
            if (recogResultList != null && !recogResultList.isEmpty()) {
                LinkedTreeMap recogResultMap = (LinkedTreeMap) recogResultList.get(0);
                lineWordResultList = (ArrayList) recogResultMap.get("line_word_result");
            }


            // 填充错题列表
            errorQuestions.clear();
            int errorIndex = 1;
            for (int i = 0; i < impLineInfoList.size(); i++) {
                LinkedTreeMap lineInfoMap = (LinkedTreeMap) impLineInfoList.get(i);

                // 获取识别结果（1为正确，0为错误）
                int rst = ((Double) lineInfoMap.get("total_score")).intValue();

                // 获取题目位置信息
                LinkedTreeMap rectMap = (LinkedTreeMap) lineInfoMap.get("imp_line_rect");
                int x1 = ((Double) rectMap.get("left_up_point_x")).intValue();
                int y1 = ((Double) rectMap.get("left_up_point_y")).intValue();
                int x2 = ((Double) rectMap.get("right_down_point_x")).intValue();
                int y2 = ((Double) rectMap.get("right_down_point_y")).intValue();

                // 获取识别结果文本和正确答案文本
                // 获取识别文本
                String ocrResult = "";
                if (lineWordResultList != null && i < lineWordResultList.size()) {
                    LinkedTreeMap wordResult = (LinkedTreeMap) lineWordResultList.get(i);
                    ArrayList wordContentArr = (ArrayList) wordResult.get("word_content");
                    if (wordContentArr != null && !wordContentArr.isEmpty()) {
                        ocrResult = wordContentArr.get(0).toString();
                    }
                }
                String correctAnswer = calcCorrectAnswer(ocrResult); // 自动生成

                // 只收集错误题目（rst==0），如需全部收集可去掉if判断
                if (rst == 0) {
                    errorQuestions.add(new ErrorQuestion(errorIndex, x1, y1, x2, y2, ocrResult, correctAnswer));
                    errorIndex++;
                }

                if (rst == 1) {
                    correctCount++;
                } else if (rst == 0) {
                    wrongCount++;
                }
                // 绘制边框和文本
                imageBitmap = draw_image(imageBitmap, x1, y1, x2, y2, rst);
            }
            updateCountText();

            // 新增：AI处理完成后，上传图片到OSS
            if (imagePath != null && !imagePath.isEmpty()) {
                Log.d("OSSUploadDebug", "11准备上传图片，路径: " + imagePath);
                OSSImag1(imagePath);
                Log.d("OSSUploadDebug", "上传方法调用完成");
            } else {
                Log.e("OSSUploadDebug", "图片路径为空，跳过上传");
            }

            // 刷新错题序号选择器和内容
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setupQuestionIndexSelector();
                    if (!errorQuestions.isEmpty()) {
                        showQuestion(0);
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            //Toast.makeText(this, "图片处理异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        return imageBitmap;
    }

    // 绘制识别结果（边框和文本）
    private Bitmap draw_image(Bitmap sourceBitmap, int x1, int y1, int x2, int y2, int result) {
        if (sourceBitmap == null || sourceBitmap.isRecycled()) {
            return sourceBitmap;
        }

        Bitmap mutableBitmap = sourceBitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(mutableBitmap);

        if (result == 1) {
            // 绿色手写勾
            Paint checkPaint = new Paint();
            checkPaint.setColor(Color.GREEN);
            checkPaint.setStrokeWidth(10);
            checkPaint.setStyle(Paint.Style.STROKE);
            checkPaint.setAntiAlias(true);
            checkPaint.setStrokeCap(Paint.Cap.ROUND);

            // 勾的起点、拐点、终点（比例可微调）
            int width = x2 - x1;
            int height = y2 - y1;
            int startX = x2 - width / 3;
            int startY = y2 - height / 4;
            int midX = startX + width / 10;
            int midY = startY + height / 6;
            int endX = midX + width / 4;
            int endY = midY - height / 3;

            // 画勾
            canvas.drawLine(startX, startY, midX, midY, checkPaint);
            canvas.drawLine(midX, midY, endX, endY, checkPaint);

        } else if (result == 0) {
            // 红色手写圈
            Paint circlePaint = new Paint();
            circlePaint.setColor(Color.RED);
            circlePaint.setStrokeWidth(10);
            circlePaint.setStyle(Paint.Style.STROKE);
            circlePaint.setAntiAlias(true);
            circlePaint.setStrokeCap(Paint.Cap.ROUND);

            // 椭圆外扩一点点，模拟手写圈
            RectF oval = new RectF(x1 - 15, y1 - 15, x2 + 15, y2 + 15);
            canvas.drawOval(oval, circlePaint);
        }
        // 其他情况不处理
        return mutableBitmap;
    }

    // 更新统计文本显示（兼容旧TextView，同时更新彩色徽章与底部统计条）
    private void updateCountText() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String countText = "正确: " + correctCount + "  错误: " + wrongCount;
                if (detailedCountText != null) {
                    detailedCountText.setText(countText);
                }
                if (tvCorrectBadge != null) {
                    tvCorrectBadge.setText("正确 " + correctCount);
                }
                if (tvWrongBadge != null) {
                    tvWrongBadge.setText("错误 " + wrongCount);
                }

                // 底部统计信息条：黑色文本，错误数字高亮
                if (tvStats != null) {
                    String stats = correctCount + "题正确，" + wrongCount + "题存疑";
                    SpannableString ss = new SpannableString(stats);
                    try {
                        String wrongStr = String.valueOf(wrongCount);
                        int start = stats.indexOf(wrongStr + "题存疑");
                        if (start >= 0) {
                            int end = start + wrongStr.length();
                            ss.setSpan(new ForegroundColorSpan(0xFFE53935), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    } catch (Exception ignored) {}
                    tvStats.setText(ss);
                }
            }
        });
    }

    private float dpToPx(float dp) {
        return dp * getResources().getDisplayMetrics().density;
    }

    /**
     * 上传图片记录到服务器
     * @param ossImagePath OSS上的图片路径
     */
    private void uploadImageRecordToServer(String ossImagePath) {

        if (ossImagePath == null || ossImagePath.isEmpty()) {
            Log.e("UploadRecord", "OSS图片路径为空，无法上传记录");
            return;
        }

        // 获取学生ID（假设从SharedPreferences或登录状态中获取）
        int studentId = getCurrentStudentId();
        if (studentId <= 0) {
            Log.e("UploadRecord", "学生ID无效，无法上传记录");
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 计算总题目数和正确题目数
        int totalCount = correctCount + wrongCount;
        if (totalCount <= 0) {
            Log.e("UploadRecord", "题目数量为0，无法上传记录");
            return;
        }

        // 获取当前时间作为提交时间
        String submitTime = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);

        // 调用API上传记录
        ApiResponse<ImageRecord> response = apiService.uploadImageRecord(
                studentId,
                ossImagePath,
                totalCount,
                correctCount,
                submitTime
        );

        // 打印关键信息（建议根据日志级别区分输出）
        Log.d("TAG1", "上传记录API调用结果");
        Log.d("TAG1", "请求参数:");
        Log.d("TAG1", "  studentId: " + studentId);
        Log.d("TAG1", "  ossImagePath: " + ossImagePath);
        Log.d("TAG1", "  totalCount: " + totalCount);
        Log.d("TAG1", "  correctCount: " + correctCount);
        Log.d("TAG1", "  submitTime: " + submitTime);

        // 处理响应
        if (response.getCode() == 200 && response.getData() != null) {
            Log.d("UploadRecord", "记录上传成功，记录ID: " + response.getData().getId());

            recordId_ = response.getData().getId();
//            Toast.makeText(this, "记录上传成功", Toast.LENGTH_SHORT).show();
        } else {
            String errorMsg = "记录上传失败";
            if (response.getMessage() != null) {
                errorMsg += ": " + response.getMessage();
            }
            Log.e("UploadRecord", response.getMessage());
            Log.e("UploadRecord", errorMsg);
//            Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 上传错题记录到服务器
     * @param ossWrongPath OSS上的图片路径
     */
    private void uploadWrongToServer(String ossWrongPath) {
        if (ossWrongPath == null || ossWrongPath.isEmpty()) {
            Log.e("UploadRecord", "OSS图片路径为空，无法上传记录");
            return;
        }

        // 获取学生ID（假设从SharedPreferences或登录状态中获取）
        int studentId = getCurrentStudentId();
        System.out.println("studentId:"+studentId);
        if (studentId <= 0) {
            Log.e("UploadRecord", "学生ID无效，无法上传记录");
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        int recordId = recordId_;
        String answer = Correct;
        String question=getQuestion(originQuestion);
        LocalDate date=LocalDate.now();



        // 调用API上传错题
        ApiResponse<WrongQuestionRecord> response = apiService.uploadWrongQuestion(
                studentId,
                recordId,
                ossWrongPath,
                answer,
                question,
                date
        );

        // 打印关键信息（建议根据日志级别区分输出）
        Log.d("TAGo", "上传记录API调用结果");
        Log.d("TAGo", "请求参数:");
        Log.d("TAGo", "  studentId: " + studentId);
        Log.d("TAGo", "  recordId: " + recordId);
        Log.d("TAGo", "  ossWrongPath: " + ossWrongPath);
        Log.d("TAGo", "  answer: " + answer);
        Log.d("TAGo", "  question: " + question);

        // 处理响应
        if (response.getCode() == 200 && response.getData() != null) {
            Log.d("UploadRecord", "记录上传成功，记录ID22: " + response.getData().getWrongId());
            Toast.makeText(this, "记录上传成功", Toast.LENGTH_SHORT).show();
        } else {
            String errorMsg = "记录上传失败";
            if (response.getMessage() != null) {
                errorMsg += ": " + response.getMessage();
            }
            Log.e("UploadRecord", errorMsg);
            Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取当前学生ID（示例方法，需根据实际登录逻辑实现）
     */
    private int getCurrentStudentId() {
        // 从SharedPreferences或登录状态中获取学生ID
        return Integer.parseInt(sessionManager.getCurrentUser().getUserId());
    }

    //错题序号选择
    private void setupQuestionIndexSelector() {
        questionIndexContainer.removeAllViews();
        HorizontalScrollView scrollView = findViewById(R.id.questionIndexScroll);
        if (errorQuestions.size() == 0) {
            scrollView.setVisibility(View.GONE);
            return;
        } else {
            scrollView.setVisibility(View.VISIBLE);
        }
        for (int i = 0; i < errorQuestions.size(); i++) {
            final int idx = i;
            Button btn = new Button(this);
            btn.setText(String.valueOf(i + 1));
            btn.setTextSize(16);
            btn.setAllCaps(false);
            btn.setBackgroundResource(R.drawable.question_index_selector);
            btn.setSelected(idx == currentQuestionIndex);
            btn.setTextColor(idx == currentQuestionIndex ? Color.parseColor("#222222") : Color.parseColor("#888888"));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(8, 0, 8, 0);
            btn.setLayoutParams(lp);
            btn.setPadding(32, 8, 32, 8);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showQuestion(idx);
                    IDX = idx;
                    Log.d("IDX", "IDX: " + IDX);
                }
            });
            questionIndexContainer.addView(btn);
        }
    }

    @SuppressLint("SetTextI18n")
    private void showQuestion(int idx) {

        if (idx < 0 || idx >= errorQuestions.size()) return;
        currentQuestionIndex = idx;
        // 高亮按钮
        for (int i = 0; i < questionIndexContainer.getChildCount(); i++) {
            View v = questionIndexContainer.getChildAt(i);
            v.setSelected(i == idx);
            if (v instanceof Button) {
                ((Button) v).setTextColor(i == idx ? Color.parseColor("#222222") : Color.parseColor("#888888"));
            }
        }
        ErrorQuestion q = errorQuestions.get(idx);
        System.out.println("sadas"+q.isUploaded);

        // 无论是否已上传，都要显示错题截图
        try {
            Bitmap src = ((BitmapDrawable) picture.getDrawable()).getBitmap();
            if (src != null && !src.isRecycled()) {
                Bitmap cropped = Bitmap.createBitmap(src, q.x1, q.y1, q.x2 - q.x1, q.y2 - q.y1);
                croppedQuestionImage.setImageBitmap(cropped);
            }
        } catch (Exception e) {
            Log.e("showQuestion", "裁剪图片失败: " + e.getMessage());
        }

        Correct = q.correctAnswer;
        originQuestion=q.ocrResult;
        // 美观显示识别结果
        String displayResult = q.ocrResult.replace("\\times", "×").replace("\\div", "÷").replace(" ", "");
        ocrResultText.setText("识别结果：" + displayResult);
        correctAnswerText.setText("正确答案：" + q.correctAnswer);
    }

    //提取表达式的前半部分
    private  static String getQuestion(String ocrResult){
        if (ocrResult == null) return "";
        // 替换LaTeX乘除号为普通符号
        String expr = ocrResult.replaceAll(" ", "").replace("\\times", "×").replace("\\div", "÷");
        java.util.regex.Pattern p = java.util.regex.Pattern.compile("(\\d+)([+×*/÷-])(\\d+)=\\d+");
        java.util.regex.Matcher m = p.matcher(expr);
        if (m.find()) {
            int a = Integer.parseInt(m.group(1));
            String op = m.group(2);
            int b = Integer.parseInt(m.group(3));
            return a+" "+op+" "+b;
        }
        return "";
    }

    // 简单实现两个数的加减乘除
    private static String calcCorrectAnswer(String ocrResult) {
        if (ocrResult == null) return "";
        // 替换LaTeX乘除号为普通符号
        String expr = ocrResult.replaceAll(" ", "").replace("\\times", "×").replace("\\div", "÷");
        java.util.regex.Pattern p = java.util.regex.Pattern.compile("(\\d+)([+×*/÷-])(\\d+)=\\d+");
        java.util.regex.Matcher m = p.matcher(expr);
        if (m.find()) {
            int a = Integer.parseInt(m.group(1));
            String op = m.group(2);
            int b = Integer.parseInt(m.group(3));
            int result = 0;
            switch (op) {
                case "+": result = a + b; break;
                case "-": result = a - b; break;
                case "×":result = a * b; break;
                case "*": result = a * b; break;
                case "/": if (b != 0) result = a / b; break;
                case "÷": if (b != 0) result = a / b; break;
            }
            return Integer.toString(result);
        }
        return "";
    }

    //添加错题集逻辑
    private void OSSImag2(Bitmap bitmap) {
        flag = 2;
        Log.d("flag", "flag2: " + flag);
        if (bitmap == null) {
            Log.e("OSSUpload", "Bitmap为空，无法上传");
            return;
        }

        Log.d("OSSUpload", "开始上传裁剪后的Bitmap");

        // 将Bitmap转换为临时文件
        File tempFile = convertBitmapToFile(bitmap);
        if (tempFile == null) {
            Log.e("OSSUpload", "无法创建临时文件");
            return;
        }

        System.out.println("aaaaaaaaaaaaaaaaaaaa");

        //
        uploadWrongToServer("https://quik-calc.oss-cn-beijing.aliyuncs.com/app/record/2025-07-04-1751596972875.jpg");

        ossUtil.uploadImage(tempFile.getAbsolutePath(), new OSSCallback() {
            @Override
            public void onSuccess(final List<String> allPath) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 上传成功
                        if (allPath != null && !allPath.isEmpty()) {
                            ossImageUrl = allPath.get(0).replaceFirst("(?<!/)app/", "/app/");;
                            Log.d("OSSUpload", "上传成功，OSS路径2: " + ossImageUrl);

                            // 在这里可以添加上传成功后的业务逻辑
                            // 调用uploadImageRecord上传记录到服务器
                            Log.d("OSSUpload", "上传成功，OSS路径2: " + flag);
                            if (flag == 1) {
                                uploadImageRecordToServer(ossImageUrl);
                            } else {
                                uploadWrongToServer(ossImageUrl);
                            }

                            // 上传完成后删除临时文件
                            if (tempFile.exists()) {
                                tempFile.delete();
                            }
                        } else {
                            Log.e("OSSUpload", "上传成功但返回路径为空");
                        }
                    }
                });
            }

            @Override
            public void onFailure(ClientException clientException, ServiceException serviceException) {
                // 上传失败
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder errorMsg = new StringBuilder("上传失败");
                        Log.e("OSSUpload", "上传失败 - 详细信息:");

                        if (clientException != null) {
                            errorMsg.append(" - 客户端异常: ").append(clientException.getMessage());
                            Log.e("OSSUpload", "客户端异常", clientException);
                        }

                        if (serviceException != null) {
                            errorMsg.append(" - 服务端异常: ")
                                    .append(serviceException.getErrorCode())
                                    .append(" (").append(serviceException.getRawMessage()).append(")");
                            Log.e("OSSUpload", "服务端异常 - ErrorCode: " + serviceException.getErrorCode(), serviceException);
                        }

                        Log.e("OSSUpload", errorMsg.toString());
                        //Toast.makeText(ImageAlbumShow.this, errorMsg.toString(), Toast.LENGTH_LONG).show();

                        // 上传失败后删除临时文件
                        if (tempFile.exists()) {
                            tempFile.delete();
                        }
                    }
                });
            }
        });
    }

    // 将Bitmap转换为临时文件的辅助方法
    private File convertBitmapToFile(Bitmap bitmap) {
        try {
            // 创建临时文件
            File tempDir = getExternalCacheDir();
            if (tempDir == null) {
                tempDir = getCacheDir();
            }
            File tempFile = new File(tempDir, "temp_image_" + System.currentTimeMillis() + ".jpg");

            // 将Bitmap写入临时文件
            FileOutputStream fos = new FileOutputStream(tempFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();

            return tempFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 清空当前数据
    private void clearCurrentData() {
        correctCount = 0;
        wrongCount = 0;
        errorQuestions.clear();
        currentQuestionIndex = 0;
        setupQuestionIndexSelector();
        showQuestion(0);
        picture.setImageBitmap(null); // 清空图片
        croppedQuestionImage.setImageBitmap(null); // 清空裁剪图片
        ocrResultText.setText("");
        correctAnswerText.setText("");
        Log.d("ClearData", "当前数据已清空");
    }
}